package com.moonLight.weblog.common.mail;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Component
@Slf4j
public class MailHelper {
    @Autowired
    private MailProperties mailProperties;
    @Autowired
    private JavaMailSender javaMailSender;

    public boolean sendMail(String to, String subject, String content) {
        log.info("==> 开始发送邮件...");
        MimeMessage mimeMailMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = null;

        try{
            mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
            //设置邮件发送来源
            mimeMessageHelper.setFrom(mailProperties.getUsername());
            //设置邮件发送目标
            mimeMessageHelper.setTo(to);
            //设置标题
            mimeMessageHelper.setSubject(subject);
            //设置内容  内容是否是html
            mimeMessageHelper.setText(content,true);
            javaMailSender.send(mimeMailMessage);
            log.info("==> 邮件发送成功...");
        } catch (MessagingException e) {
            log.error("==> 邮件发送失败...");
            return false;
        }

        return true;
    }




}
